<template>
	<view class="container">
        <u--form :labelStyle="{fontSize: '28rpx', color: '#312C2A', height: '80rpx'}" labelWidth="100"
                 labelPosition="left" :model="model" :rules="rules" ref="uForm" errorType="message">
			<view class="form">
                <u-form-item label="收货人" prop="name" borderBottom>
                    <u--input inputAlign="right" placeholder="输入收货人姓名" v-model="model.name"
                              border="none"></u--input>
                </u-form-item>
                <u-form-item label="电话号码" prop="mobile" borderBottom>
                    <u--input type="number" maxlength="11" inputAlign="right" placeholder="请输入11位手机号码" v-model.number="model.mobile"
                              border="none"></u--input>
                </u-form-item>
                <u-form-item label="选择省市区" prop="area" borderBottom @click="showAddressPop">
                    <u--input v-model="model.area" disabled placeholder="请选择" inputAlign="right"
                              disabledColor="transparent" border="none"></u--input>
                    <template #right>
                        <u-icon name="arrow-right" @click="showAddressPop"></u-icon>
                    </template>
                </u-form-item>

                <u-form-item label="详细地址" prop="address" borderBottom>
                    <u--input inputAlign="right" placeholder="请输入详细地址" v-model="model.address" border="none"></u--input>
                </u-form-item>
			</view>

			<view class="form shadow" style="margin-top: 30rpx;">
				<u-form-item label="设为默认地址" prop="name" :borderBottom="false" >
					<view class="self-set">
                        <u-switch activeColor="#D66A44"
                                  :active-value="1"
                                  :inactive-value="0"
                                  v-model="model.default"></u-switch>
					</view>
				</u-form-item>
			</view>
		</u--form>
	</view>

	<view class="btn">
		<u-button throttleTime="1000" :customStyle="{height: '86rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}" :hairline="false" type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)" @click="confirm">保存</u-button>
	</view>

    <!-- 地址三级联动 -->
    <!-- 省市区选择 province city area初始省市区设置 show:是否显示  @changeClick：更改省市区事件 @sureSelectArea：确认事件 @hideShow：隐藏事件-->
    <view v-if="showComponent">
        <cc-selectDity :province="province" :city="city" :area="area" :show="addressPop" @changeClick="changeClick" @sureSelectArea="confirmArea" @hideShow="addressPop = false"></cc-selectDity>
    </view>

</template>

<script setup>
    import { onLoad, onReady } from '@dcloudio/uni-app'
    import { ref, nextTick } from 'vue'
    import {getAddressInfo, saveAddress} from "@/api/user";
    const uForm = ref(null)

    const model = ref({
        name: '',
        mobile: '',
        province: '北京市',
        city: '北京市',
        district: '',
        address: '',
        area: '',
        default: 0
    })

    const showComponent = ref(true)

    const actions = ref([{
        name: '男'
    },
        {
            name: '女'
        },
    ])
    const rules = ref({
        name: [
            {
                type: 'string',
                required: true,
                message: '请输入姓名',
                trigger: ['blur','change'],
            }
        ],
        area: [
            {
                type: 'string',
                required: true,
                message: '请选择地址',
                trigger: ['change'],
            }
        ],
        address: [
            {
                type: 'string',
                required: true,
                message: '请输入详细地址',
                trigger: ['change'],
            }
        ],
        mobile: [
            {
                type: 'number',
                required: true,
                message: '请输入手机号',
                trigger: ['blur','change'],
            },
            {
                // 自定义验证函数，见上说明
                validator: (rule, value, callback) => {
                    // 上面有说，返回true表示校验通过，返回false表示不通过
                    // uni.$u.test.mobile()就是返回true或者false的
                    return uni.$u.test.mobile(value);
                },
                message: '手机号码不正确',
                // 触发器可以同时用blur和change
                trigger: ['change','blur'],
            }
        ]
    })
    const sexSelect = (e) => {
        model.value.name = e.name
    }

    // 提交保存.
    const confirm = () => {
        uForm.value.validate().then(async ({ valid }) => {
            if (valid) {
                uni.showToast({
                    mask: true,
                    title: '验证失败',
                    icon: 'error'
                })
                return false
            } else {
                let param = {
                    name: model.value.name,
                    mobile: model.value.mobile,
                    province: model.value.province,
                    city: model.value.city,
                    district: model.value.district,
                    address: model.value.address,
                    default: model.value.default ?? 0,
                }
                if (editId.value > 0) {
                    param.id = editId.value
                }
                const {code, data, message } = await saveAddress(param)
                if (code == 1) {

                    let pages = getCurrentPages(); // 当前页面
                    let beforePage = pages[pages.length - 2]; // 上一页
                    uni.navigateBack({
                        success: function() {
                            beforePage.onLoad(); // 执行上一页的onLoad里面的方法方法
                        }
                    });

                    /*
                    if (sourceType.value == 'payment') {
                        uni.redirectTo({
                            url: `/mine/address/list?source=${sourceType.value}&checkoutType=${checkoutType.value}&skuId=${skuId.value}&quantity=${quantity.value}&cartIdsStr=${cartIdsStr.value}`
                        });
                    } else {
                        let pages = getCurrentPages(); // 当前页面
                        let beforePage = pages[pages.length - 2]; // 上一页
                        uni.navigateBack({
                            success: function() {
                                beforePage.onLoad(); // 执行上一页的onLoad里面的方法方法
                            }
                        });
                    }
                     */

                } else {
                    uni.showToast({
                        mask: true,
                        title: message ?? '保存失败',
                        icon: 'error'
                    })
                }
            }
        }).catch(err => {
            console.log('验证失败',err)
        })

        // uni.navigateBack()
    }

    // 展示弹窗
    const addressPop = ref(false)
    const province = ref('北京市')
    const city = ref('北京市')
    const area = ref('东城区')
    // 地址选择
    const selectProvince = ref('')
    const selectCity = ref('')
    const selectArea = ref('')

    const showAddressPop = () => {
        console.log(model.value)
        addressPop.value = true
    }
    // 获取省市区
    const changeClick = (province, city, area) => {
        selectProvince.value = province
        selectCity.value = city
        selectArea.value = area
    }
    // 确认
    const confirmArea = (e) => {
        console.log(e)
        addressPop.value = false

        if (selectArea.value) {
            model.value.province = selectProvince.value
            model.value.city = selectCity.value
            model.value.district = selectArea.value

            province.value = selectProvince.value
            city.value = selectCity.value
            area.value = selectArea.value
        } else {
            model.value.province = e.detail.target.dataset.province
            model.value.city = e.detail.target.dataset.city
            model.value.district = e.detail.target.dataset.area

            province.value = e.detail.target.dataset.province
            city.value = e.detail.target.dataset.city
            area.value = e.detail.target.dataset.area
        }


        model.value.area = model.value.province + ' ' + model.value.city + ' ' + model.value.district
        uForm.value.validateField('area')
    }

    const editId = ref(0)

    onReady(() => {
        uForm.value.setRules(rules)
    })

    const sourceType = ref('')
    const checkoutType = ref('')
    const skuId = ref(0)
    const quantity = ref(0)
    const cartIdsStr = ref('')

    onLoad((evt) => {
        if (evt?.id && evt.id > 0) {
            editId.value = evt.id
            handleGetAddressData(evt.id)
        }
        sourceType.value = evt?.source || ''
        checkoutType.value = evt?.checkoutType || ''
        skuId.value = evt?.skuId || ''
        quantity.value = evt?.quantity || ''
        cartIdsStr.value = evt?.cartIdsStr || ''
        console.log('add address',evt)
    })

    // 地址详情
    const handleGetAddressData = async (id) => {
        const {code, data, message} = await getAddressInfo({id:id})
        if (code == 1) {
            model.value.name = data.name
            model.value.mobile = data.mobile
            model.value.province = data.province
            model.value.city = data.city
            model.value.district = data.district
            model.value.area = data.province + ' ' + data.city + ' ' + data.district
            model.value.address = data.address
            model.value.default = data.default

            province.value = data.province
            city.value = data.city
            area.value = data.district

            showComponent.value = false
            nextTick(() => {
                showComponent.value = true
                console.log('nextTick')
            })
        }
    }
</script>

<style lang="scss" scoped>
	.container {
		padding: 50rpx 26rpx;
		.form {
			padding: 0 44rpx;
			background: #FFFFFF;
			border-radius: 30rpx;
		}
	}
	.self-set {
		@include end(100%);
	}
	.btn {
		padding: 0 55rpx;
		width: 100%;
		position: fixed;
		left: 50%;
		bottom: 70rpx;
		transform: translateX(-50%);
		z-index: 9;
	}
	.shadow {
		box-shadow: 0rpx 0rpx 30rpx 1rpx rgba(153,153,153,0.16);
	}
</style>
